package cn.com.yinhex.as.util;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class VMFactory {

	private String templatebody = null;

	Template tpl = null;

	private VelocityContext context = null;

	private static VelocityEngine engine = null;

	private boolean debug = false;

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	/**
	 * ����
	 */
	public VMFactory(Properties properties) {
		context = new VelocityContext();
		/* ���ȴ���һ��ģ�������ʵ�����Գ�ʼ�� */
		try {
			engine = new VelocityEngine();
			Iterator it = properties.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				engine.setProperty(entry.getKey().toString(), entry.getValue());
			}
			engine.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * �趨ģ��
	 * 
	 * @param template
	 */
	public void setTemplate(String templatefile) {
		try {
			tpl = engine.getTemplate(templatefile, "UTF-8");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		this.templatebody = null;
	}

	/**
	 * �趨ģ������
	 * 
	 * @param templatebody
	 */
	public void setTemplateBody(String templatebody) {
		try {
			this.templatebody = templatebody;
			this.tpl = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * ������
	 * 
	 * @param name
	 * @param obj
	 */
	public void put(String name, Object obj) {
		/* ���������ģ������� */
		context.put(name, obj);
	}

	/**
	 * ����ַ�
	 */
	public String toString() {
		StringWriter out = new StringWriter();
		try {
			output(out);
			return out.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			try {
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * �����
	 * 
	 * @param out
	 * @return
	 */
	public void output(Writer out) throws IOException {
		try {
			/*
			 * �������Ŀ���ǿ���ʹ��Ƕ�׵�ģ�����
			 */
			if (this.tpl != null) {
				// ���һ��ģ��
				// ��ģ�����ݺϲ������Writer
				tpl.merge(context, out);
			} else {
				// ֱ��ʹ��templatebody�ϲ�
				engine.evaluate(context, out, "", templatebody);
			}
		} catch (Exception e) {
			if (debug) {
				out.write("<!--" + e.toString() + "-->");
			} else {
				out = null;
			}
			e.printStackTrace();
		}
	}
}
